<template>
  <div class="container">
    <div class="perfect-avatar">
      <van-uploader
        v-model="fileList"
        :after-read="afterRead"
        result-type="file"
        multiple
        max-count="1"
      />
    </div>
    <van-form
      class="passport-form"
      validate-first
      ref="form"
      @failed="onFailed"
      @submit="onSubmit"
    >
      <div class="passport-form-fields">
        <van-field
          v-model="user.nickname"
          name="nickname"
          required
          label="昵称"
          placeholder="请输入昵称"
          :rules="rules.nickname"
        >
          <template #right-icon>
            <van-loading
              type="spinner"
              v-if="validating"
            />
          </template>
        </van-field>
        <van-field
          name="gender"
          label="性别"
          required
          :rules="rules.gender"
          :error-message="genderTips+'(保存成功后，不可修改)'"
        >
          <template #input>
            <van-radio-group
              v-model="user.gender"
              direction="horizontal"
              checked-color="#ff6600"
            >
              <van-radio :name="1">男</van-radio>
              <van-radio :name="2">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>
      </div>

      <div class="passport-form-action">
        <van-button
          round
          block
          type="warning"
          native-type="submit"
          :disabled="disableSubmit"
        >
          保 存
        </van-button>
      </div>
    </van-form>
    <div class="passport-tips">
      <span>点击“完成”按钮，即表示同意</span>
      <router-link
        :to="{name: 'help'}"
        class="rlink"
      >《隐私权声明》</router-link>
    </div>

    <!-- DEBUG -->

  </div>
</template>

<script>
import Debug from '@/components/debug'

import {
  Row,
  Col,
  Cell,
  Button,
  Radio,
  RadioGroup,
  CellGroup,
  Form,
  Field,
  Area,
  Icon,
  Image,
  Loading,
  Popup,
  ActionSheet,
  Uploader,
  Lazyload
} from 'vant'

export default {
  name: 'WechatAuth',
  components: {
    Debug,
    [Button.name]: Button,
    [Radio.name]: Radio,
    [RadioGroup.name]: RadioGroup,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Loading.name]: Loading,
    [Row.name]: Row,
    [Col.name]: Col,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Form.name]: Form,
    [Area.name]: Area,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Image.name]: Image,
    [ActionSheet.name]: ActionSheet,
    [Uploader.name]: Uploader,
    Lazyload
  },
  data () {
    return {
      fileList: [],
      user: {
        nickname: '',
        gender: '',
        avatar: ''
      },
      errors: null,
      disableSubmit: false,
      genderTips: '',
      validating: false,
      rules: {
        nickname: [
          {
            required: true,
            message: '请设置一个您的个性昵称'
          }
        ],
        gender: [
          {
            required: true,
            message: '请选择性别'
          }
        ]
      }
    }
  },
  watch: {
    user: {
      handler (cv, ov) {
        console.log('userdata', cv)
        if (cv && cv.avatar) {
          this.fileList = [
            {
              url: cv.avatar
            }
          ]
        }
      },
      deep: true
    },
    errors: {
      handler (cv, ov) {
        console.log('failed', cv)
        if (cv.length > 0) {
          let firstError = cv[0]
          if (firstError.name === 'gender') {
            this.genderTips = firstError.message + ' '
          }
        }
      },
      deep: true
    }
  },
  created () {
    this.onLoad()
  },
  methods: {
    onLoad () {
      let params = {
        connect_id: sessionStorage.getItem('wxUserInfo')
      }
      this.$http.user
        .profile(params)
        .then(res => {
          if (res.data) {
            this.user = Object.assign({}, this.user, res.data)
          } else {
            console.log(res)
          }
        })
    },
    async afterRead (file) {
      console.group('Perfect afterRead')
      console.log(file)
      file.status = 'uploading'
      file.message = '上传中...'
      // 创建form对象
      let param = new FormData()
      // 对应后台接收图片名 通过append向form对象添加数据
      param.append('imageFile', file.file)

      await this.$http.base
        .uploadFile(param)
        .then(res => {
          console.log(res)
          if (res.data) {
            file.status = 'done'
            file.message = ''
            file.url = res.data.url
            this.user.avatar = res.data.path
          } else {
            file.status = 'fail'
            file.message = '上传失败'
          }
        })
        .catch(e => {
          console.log(e)
          file.status = 'fail'
          file.message = '上传失败'
        })

      console.log(this.fileList)
      console.groupEnd('Perfect afterRead')
    },

    onFailed (errorInfo) {
      console.log('failed', errorInfo)
      this.errors = errorInfo.errors
      console.log('failed', this.$refs.form)
    },
    goBack () {
      var referrer = sessionStorage.getItem('referrer')
      if (referrer != null) {
        this.$router.replace({
          path: referrer
        })
        sessionStorage.removeItem('referrer')
      } else {
        this.$router.replace({
          path: '/'
        })
      }
      // console.log(this.$store.state.backRoute)
      // let route = this.$store.state.backRoute
      // if (!route) {
      //   this.$router.replace(route)
      // } else {
      //   this.$router.replace({ path: '/' })
      // }
    },
    onSubmit (data) {
      this.disableSubmit = true
      let params = Object.assign({}, this.user, data)
      console.log('submit', params)
      this.$http.user.updateProfile(params).then(res => {
        if (res.data) {
          this.goBack()
        } else {
          this.$toast('提交失败~')
          this.disableSubmit = false
        }
      }).catch(e => {
        console.log(e)
        this.$toast('提交失败~')
        this.disableSubmit = false
      })
    },
    // 异步校验函数返回 Promise
    validatorNickname (val) {
      return new Promise(resolve => {
        this.validating = true
        setTimeout(() => {
          this.validating = false
          resolve(/\d{6}/.test(val))
        }, 1000)
      })
    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.perfect-avatar {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  /deep/ .van-uploader {
    &__upload {
      background: linen;
      margin: 0;
      border-radius: 50%;
    }
    &__mask {
      border-radius: 50%;
    }
    &__preview {
      margin: 0;
      &-image {
        border-radius: 50%;
        background: linen;
        padding: 3px;
        .van-image__img {
          border-radius: 50%;
        }
      }
      &-delete {
        right: 0;
        top: 0;
      }
    }
  }
}
.passport-form {
  padding: 0;
  margin-top: 15px;
  &-fields {
    background: #fff;
    padding: 0 15px;
    /deep/ .van-field__label {
      margin-right: 30px;
    }
    /deep/ .van-field__error-message {
      margin-top: 3px;
      font-size: 12px;
      opacity: 0.8;
      line-height: initial;
      transform: scale(0.83);
      transform-origin: 0;
    }
  }
  &-action {
    padding-left: 15px;
    padding-right: 15px;
  }
}
</style>
